/**
 *    加载称重房页面
 */

import { Button, Empty, Image, message, Modal, Switch } from "antd";
import { WeightBox, WeigingRoomBox } from "./style";
import { useCallback, useEffect, useRef, useState } from "react";
import { WebRtcStreamerxiaoxujs } from "../../../assets/fun/webrtcstreamer";
import {  wsIp } from "../../../api/http";
import { useLocation, useNavigate } from "react-router-dom";
import { getGbSystemSetCatchGet, getGbSystemSetRtspGet, getGbSystemSetSetGbStop, getGbSystemSetTgLg } from "../api";
import { ExclamationCircleFilled } from '@ant-design/icons';

const { confirm } = Modal;

const WeigingRoomPage = () => {
    const history = useNavigate();
    const location = useLocation();
    const [weight, setWeight] = useState(0); //实时重量
    const [carNum, setCarNum] = useState('暂无车牌'); //车牌号 
    const [status, setStatus] = useState('暂无状态'); //称重状态 
    const [objInfo, setObjInfo] = useState<any>({});//提货单信息
    const [dataList, setDataList] = useState<any[]>([]) //日志数据
    const [imgData, setImgData] = useState<any[]>([]) //图片数据
    const ws = useRef<WebSocket | null>(null); //ws连接
    const videoEle = useRef(null);//视频连接
    const videoEleAdd = useRef<any>();
    const [rtspValue, setRtspValue] = useState("")
    const [catchData, setCatchData] = useState<{ catchName: string }[]>([])
    const [tailuoLoading, setTailuoLoading] = useState(false); // 尾流加载中
    const [kaiguanShow, setKaiguanShow] = useState(false); // 卡关显示
    const [kaiguanLoading, setKaiguanLoading] = useState(false); // 卡关加载中
    useEffect(() => {
        if (location.state) {
            if (location.state.isClosed === 0) {
                setKaiguanShow(true);
            } else {
                setKaiguanShow(false);
            }
        }
    }, [location.state, location.state.isClosed])
    const wsFun = useCallback(() => {
        const token = sessionStorage.getItem("token");
        // console.log(basicIp, "basicIp")
        let url = wsIp + `/websocket/weightHouse?satoken=${token}&poundId=${location.state.poundId}`;
        if (token) {
            ws.current = new WebSocket(url);
            ws.current.onopen = (e) => {
                console.log("ws连接成功");
            }
            ws.current.onmessage = (e) => {
                let wsData = JSON.parse(e.data);
                // console.log(wsData);
                console.log(wsData);

                switch (wsData.messageType) {
                    case 0:
                        setWeight(wsData.info);
                        break;
                    case 1:
                        setCarNum(wsData.info);
                        break;
                    case 2:
                        setStatus(wsData.info);
                        break;
                    case 3:
                        setObjInfo(wsData.info);
                        break;
                    case 4:
                        setDataList(prevDataList => [...prevDataList, wsData.info]);
                        break;
                    case 5:
                        setImgData(wsData.info);
                        break;
                    case 6:
                        confirm({
                            title: '警告',
                            icon: <ExclamationCircleFilled />,
                            content: wsData.info,
                            onOk() {
                            },
                            onCancel() {
                            },
                        });
                        break;
                    default:
                }
            }
            ws.current.onclose = () => {
                message.error('ws连接断开')
            }
        }
        return () => {
            ws.current?.close();
        };
    }, [location.state.poundId])

    useEffect(() => {

        if (rtspValue) {
            if (videoEle.current) {
                console.log(videoEle.current);
                videoEleAdd.current = new WebRtcStreamerxiaoxujs(
                    videoEle.current!,
                    "http://localhost:8001"
                );
                videoEleAdd.current.connect(rtspValue);
            }
        }
        return () => {
            if (videoEleAdd.current) {
                videoEleAdd.current.disconnect();
            }
        };
    }, [rtspValue])

    const controlBoxRef = useRef<HTMLDivElement | null>(null); //控制盒子


    useEffect(() => {
        if (controlBoxRef.current) {
            controlBoxRef.current.scrollTop = controlBoxRef.current.scrollHeight;
        }
    }, [dataList]);

    useEffect(() => {
        wsFun();
    }, [wsFun])

    const videoFun = useCallback(async (value: string) => {
        //getGbSystemSetRtspGet 
        const { code, msg, data } = (await getGbSystemSetRtspGet({ id: value })) as {
            code: number;
            msg: string;
            data: string
        };
        if (code === 20000) {
            setRtspValue(data)
        } else {
            message.error(msg);
        }

    }, [])

    const catchFun = useCallback(async (value: string) => {
        const { code, msg, data } = (await getGbSystemSetCatchGet({ id: value })) as {
            code: number;
            msg: string;
            data: { catchName: string }[]
        };
        if (code === 20000) {
            setCatchData(data)
        } else {
            message.error(msg);
        }

    }, [])

    useEffect(() => {
        if (location.state.poundId) {
            videoFun(location.state.poundId)
            catchFun(location.state.poundId)
        }
    }, [videoFun, catchFun, location.state.poundId])

    const handleTailuo = async (type: string) => {
        setTailuoLoading(true); // 尾流加载中
        const { code, msg } = (await getGbSystemSetTgLg({ id: location.state.poundId, type })) as {
            code: number;
            msg: string;
        };
        if (code === 20000) {
            message.success('操作成功');
        } else {
            message.error(msg);
        }
        console.log('解锁')
        setTailuoLoading(false); // 尾流加载完成
    }
    // 磅房状态切换
    const handleChangeKaiguan = async () => {
        setKaiguanLoading(true); // 卡关加载中
        const { code, msg } = (await getGbSystemSetSetGbStop({ id: location.state.poundId, type: kaiguanShow ? 1 : 0 })) as {
            code: number;
            msg: string;
        };
        if (code === 20000) {
            message.success('操作成功');
            setKaiguanShow(!kaiguanShow); // 卡关状态切换
        } else {
            message.error(msg);
        }
        setKaiguanLoading(false); // 卡关加载完成
    }

    return (
        <WeigingRoomBox>
            <div className="header_box">
                <div className="back" onClick={() => history(-1)}>&lt; 返回</div>
                <div style={{ marginRight: '2rem', display: 'flex', alignItems: 'center' }} >
                    <span style={{ fontSize: '1.6rem', marginRight: '1rem' }}>启用状态:</span>
                    <Switch loading={kaiguanLoading} checkedChildren="开启" unCheckedChildren="关闭" checked={kaiguanShow} onChange={() => handleChangeKaiguan()} /></div>
            </div>

            <div className="weiging-room">
                <div className="weiging top">
                    <div className="item-title" style={{ justifyContent: 'space-between' }}>
                        <div style={{ display: 'flex', alignItems: 'center' }}><div>{location.state.poundName}</div>
                            <div className="title-button">允许容错范围: ± {location.state.toleranceRange}kg</div></div>
                        <div>
                            <Button loading={tailuoLoading} type='primary' style={{ marginRight: '2rem' }} onClick={() => handleTailuo('1')}>抬杆</Button>
                            <Button loading={tailuoLoading} type="primary" style={{ marginRight: '2rem' }} onClick={() => handleTailuo('2')}>落杆</Button>
                        </div>

                    </div>
                    {/* 称重主体 */}
                    <WeightBox>
                        <div className="top-box">
                            <div className="top-box-left">
                                <div className="top-box-left-title">当前称重</div>
                                <div className="top-box-left-main">
                                    {/* weight单位是千克 */}
                                    <div className="count">
                                        {
                                            (weight / 1000).toFixed(3)
                                        }
                                        <div className="dun">吨</div>
                                    </div>
                                </div>
                            </div>
                            <div className="top-box-right">
                                <div className="top-box-right-title">车辆信息</div>
                                <div className="top-box-right-main">
                                    <div className="right-box">
                                        <span className=" right-box-icon iconfont">&#xe602;</span>
                                        <div className="right-box-title">车牌号</div>
                                        <div className="right-box-main">{carNum}</div>
                                    </div>
                                    <div className="right-box">
                                        <span className=" right-box-icon greenicon iconfont">&#xe600;</span>
                                        <div className="right-box-title">称重状态</div>
                                        <Button className="right-button">{status}</Button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="bottom-box">
                            <div className="bottom-box-title">提货单信息</div>
                            <div className="bottom-box-main">
                                <div className="itemBox">
                                    <div className="itemBox-title">
                                        <span className="iconfont">&#xe7e2;</span>
                                        <span style={{ marginLeft: '0.5rem' }}>货品名称</span>
                                    </div>
                                    <div className="itemBox-main">{objInfo?.good ? objInfo?.good : '--'}</div>
                                </div>
                                <div className="itemBox">
                                    <div className="itemBox-title">
                                        <span className="iconfont">&#xe651;</span>
                                        <span style={{ marginLeft: '0.5rem' }}>司机姓名</span>
                                    </div>
                                    <div className="itemBox-main">{objInfo?.driverName ? objInfo?.driverName : '--'}</div>
                                </div>
                                <div className="itemBox">
                                    <div className="itemBox-title">
                                        <span className="iconfont">&#xe60a;</span>
                                        <span style={{ marginLeft: '0.5rem' }}>手机号</span>
                                    </div>
                                    <div className="itemBox-main phone">
                                        {objInfo?.telPhone ? (
                                            `${objInfo.telPhone.substring(0, 3)} ${objInfo.telPhone.substring(3, 7)} ${objInfo.telPhone.substring(7)}`
                                        ) : (
                                            '--'
                                        )}

                                    </div>
                                </div>
                                <div className="itemBox">
                                    <div className="itemBox-title">
                                        <span className="iconfont">&#xe6ca;</span>
                                        <span style={{ marginLeft: '0.5rem' }}>允许提货量</span>
                                    </div>
                                    <div className="itemBox-main">{objInfo?.allowAmount ? objInfo?.allowAmount : '--'}  吨</div>
                                </div>
                                <div className="itemBox">
                                    <div className="itemBox-title">
                                        <span className="iconfont">&#xe62f;</span>
                                        <span style={{ marginLeft: '0.5rem' }}>本次提货量</span>
                                    </div>
                                    <div className="itemBox-main">{objInfo?.thisWeight ? objInfo?.thisWeight : '--'} 吨</div>
                                </div>
                                <div className="itemBox">
                                    <div className="itemBox-title">
                                        <span className="iconfont">&#xe62a;</span>
                                        <span style={{ marginLeft: '0.5rem' }}>剩余提货量</span>
                                    </div>
                                    <div className="itemBox-main">{objInfo?.remainAmount ? objInfo?.remainAmount : '--'} 吨</div>
                                </div>
                            </div>
                        </div>
                    </WeightBox>
                </div>
                <div className="weiging top">
                    <div className="item-title">监控全流程</div>
                    <div className="video-box">
                        <video
                            ref={videoEle}
                            style={{
                                width: "100%",
                                height: "100%",
                                border: "1px soild rgb(0,87,104)",
                                objectFit: "cover",
                            }}
                            id={`video`}
                            controls
                            muted
                            preload="auto"
                        ></video>
                    </div>
                </div>
                <div className="weiging bottom">
                    <div className="item-title">
                        <span>实时过磅信息</span>
                        <Button className="clear" icon={<span className="iconfont">&#xe6c3;</span>}
                            onClick={() => {
                                setDataList([]);
                            }}
                        >清空信息</Button>
                    </div>
                    <div className="Logbox" ref={controlBoxRef}>
                        {dataList.length > 0 ?
                            dataList.map((item, index) => {
                                return (
                                    <div key={index} style={{ display: 'flex', marginTop: '5px' }}>
                                        <div style={{ width: '35rem' }}>{item}</div>
                                    </div>
                                )
                            }) :
                            <div style={{ marginLeft: '2rem' }}>暂无日志</div>
                        }
                    </div>
                </div>
                <div className="weiging bottom">
                    <div className="item-title">抓拍照片</div>
                    <div className="img-box">
                        {
                            imgData.length > 0 ? imgData.map((item, index) => {
                                return (
                                    <div
                                        key={index}
                                        className="img-item"
                                    >
                                        <Image
                                            style={{ objectFit: 'cover', width: '100%', height: '100%' }}
                                            src={ item.url}
                                        />
                                    </div>
                                )
                            }) : <>
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            </>
                        }

                    </div>
                    <div className="img-title">
                        {
                            imgData.length > 0 ? catchData.map((item, index) => {
                                return (
                                    <div
                                        key={index}
                                    >
                                        {item.catchName}
                                    </div>
                                )
                            }) : null
                        }
                    </div>
                </div>
            </div>
        </WeigingRoomBox>
    );
};
export default WeigingRoomPage;
